import Taro from "@tarojs/taro";
import parseHtml from '../utils/parser'
import {platform} from "./platform-settting.service";
import {getStorageSync, replaceUrl, setStorageSync, setTempSellerId} from "./tools";
import {user} from "./user.service";
import {http} from "./http";
import {IDENTITY_IS_SELLER, SCAN_BIND_SELLER, TARO_ENV} from "../constants/api";
import {h5Wx} from "./h5.service";
import {newHttp} from "./request";

/*
* 首页 & 大首页 分销逻辑
* @param platformSet 平台信息
* @param scene 分销商 id 组  例：19321_19321_19321 sellerId_bindSellerId_tempSellerId
* @param tempSellerId 临时分销商id
* @param bindSellerId 绑定分销商id
* */
export async function handlerIndexPublicCode(platformSet, scene, tempSellerId, bindSellerId) {
  let bindSellerIds = getStorageSync('bindSellerId') || 0;
  if (scene && (/^\d+_\d+_\d+$/.test(scene) || /^\d+_\d+_\d+_\d+$/.test(scene))) {
    platform.scene = 0
    const paramArr = scene.split('_')
    if (paramArr[2]) {
      setTempSellerId(paramArr[2])
    }
    if (platformSet.isSellerPermanentLock) {
      if (!bindSellerIds) {
        bindSellerIds = paramArr[1]
      }
    } else {
      bindSellerIds = paramArr[1]
    }
  } else {
    if (platformSet.isSellerPermanentLock) {
      if (!bindSellerIds) {
        bindSellerIds = bindSellerId || bindSellerIds;
      }
    } else {
      bindSellerIds = bindSellerId || bindSellerIds;
    }
  }
  user.bindSellerId = bindSellerIds
  await Taro.setStorage({
    key: 'bindSellerId',
    data: user.bindSellerId
  })
  const shareParam = await user.getShareParams(tempSellerId)
  const isLogin = await user.checkLogin()
  if ((bindSellerIds || tempSellerId) && isLogin && process.env.DISTINGUISH_IDENTITY) {
    http.HPost(SCAN_BIND_SELLER, {temp_seller_id: tempSellerId, refer_seller_id: bindSellerIds})
  }
  if (tempSellerId) {
    setTempSellerId(tempSellerId)
    setStorageSync('bindSellerId', bindSellerIds)
  }
  return shareParam
}

/*
* 首页 & 大首页 分享逻辑
* @param title 标题
* @param desc 描述
* @param page 页面路径
* @param imgUrl 分享图片
* @param shareParam 分享参数
* */
export async function handlerIndexH5Share(title, desc, page, imgUrl, shareParam) {
  let mpKey = ''
  const uInfo = getStorageSync('user') || ''
  if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
    mpKey = uInfo.mpkey
  }
  const link = window.location.origin + page + '?mpkey=' + mpKey + `&${shareParam}`
  const shareData = {
    title, desc, link, imgUrl
  }
  h5Wx.share(shareData)
  return link
}

/*
* 商品详情页收藏逻辑
* @param type 0|1 收藏|取消
* @param category 商品类型
* @param id 商品id
* */
export async function handlerCollection(type, category, id) {
  if (!(await user.checkLogin())) {
    await user.jumpLogin();
    return false
  }
  await Taro.showLoading({
    title: '加载中...',
    mask: false
  })
  const api = {
    0: '/msvc-shop/v1/goods/favorite/add',
    1: '/msvc-shop/v1/goods/favorite/update'
  }
  return await newHttp.catchPost(api[type], {goods_id: id, goods_category: category})
}

/*
* 商品详情页富文本内容图片处理逻辑
* @description 仅限 h5 环境
* @param type 0|1 收藏|取消
* @param category 商品类型
* */
export function handlerRichImage() {
  if (TARO_ENV === 'h5') {
    setTimeout(() => {
      const images: any = []
      const imageTwo: any = []
      document.querySelectorAll('#html-description img').forEach((ele: any) => {
        images.push(ele.src)
        ele.addEventListener('click', function () {
          Taro.previewImage({
            urls: images,
            current: ele.src
          })
        }, false)
      })
      document.querySelectorAll('#html-notice img').forEach((ele: any) => {
        imageTwo.push(ele.src)
        ele.addEventListener('click', function () {
          Taro.previewImage({
            urls: imageTwo,
            current: ele.src
          })
        }, false)
      })
    }, 2000)
  }
}

/*
* 富文本内容解析
* @description 仅限头条环境
* @param content 要解析的富文本内容
* */
export function getContent(content) {
  return content ? parseHtml(content) : ''
}

/*
* 获取长链接
* @description 仅限h5环境
* */
export async function getLongUrl() {
  if (TARO_ENV !== 'h5') {
    return ''
  }
  const userInfo = Taro.getStorageSync('user');
  const shareParams = await user.getSellerParams()
  let href = window.location.href
  if (href.indexOf('force_platform_seller=1') > -1 && userInfo && process.env.DISTINGUISH_IDENTITY) {
    const identityIsSeller = await http.get(IDENTITY_IS_SELLER, {})
    if (identityIsSeller.isSeller) {
      href.replace('force_platform_seller=1', '')
    }
  }
  if (href.indexOf('pkeys=') > -1) {
    href = replaceUrl(href, 'pkeys', '')
  }
  return href + '&' + shareParams
}

/*
* 获取抖音分享商品spuid
* @description 仅限tt环境
* */
export function getShareSpuId(goodsList) {
  if (!goodsList || goodsList.length <= 0) {
    return []
  }
  return goodsList.filter(item => item.bd_spu_id && item.isInStoreHouse)
}

/*
* 获取各个商品信息介绍
* @param goodsInfo 商品数据集
* */
export function getGoodsInstructions(goodsInfo, isGetTicketWay, hasSite, hasTicket) {
  if (!goodsInfo) {
    return []
  }
  const isTT = process.env.TARO_ENV === 'tt'
  const instructions: any = []
  if (process.env.DETAIL_SHOW_NO) {
    instructions.push({key: '', value: goodsInfo.no, jump: false, showAlert: true})
  }
  if (!!goodsInfo.sale_count && !!platform.info.is_show_sales_volume) {
    instructions.push({key: '销量', value: goodsInfo.sale_count, jump: false, showAlert: true})
  }
  if (isTT && !!goodsInfo.surplus_stock) {
    instructions.push({key: '库存', value: goodsInfo.surplus_stock, jump: false, showAlert: true})
  }
  if (!isTT && process.env.P_ENV !== 'hiyogo' && !!platform.info.is_show_stock) {
    if (!!goodsInfo.virtual_store && !!goodsInfo.sale_style) {
      if (!!goodsInfo.actual_virtual_store) {
        instructions.push({key: '库存', value: goodsInfo.actual_virtual_store, jump: false, showAlert: true})
      }
    } else if (!!goodsInfo.surplus_stock) {
      instructions.push({key: '库存', value: goodsInfo.surplus_stock, jump: false, showAlert: true})
    }
  }
  if (goodsInfo.notice) {
    instructions.push({key: '', value: '购买须知', jump: false, showAlert: true})
  }
  const jumpLink = `/common/limited/list?goodsId=${goodsInfo.id}`
  if (hasSite && !!goodsInfo.is_store_show) {
    instructions.push({key: '适用门店', value: '', jump: true, jumpLink})
  }
  if (hasTicket && isGetTicketWay && goodsInfo.ticketWayStr) {
    instructions.push({key: '', value: goodsInfo.ticketWayStr, jump: true, jumpLink})
  }
  if (instructions.length <= 0) {
    return []
  }
  return instructions
}
/*
* 格式化日期，因为组件会2022-12-1，格式化成2022-12-01
*
* */
export function getDateInfoDate(value) {
  let date
  if (!value) {
    date = new Date()
  } else {
    date = new Date(value.replace(/-/g, '/'))
  }
  const y = date.getFullYear()
  let MM = date.getMonth() + 1
  MM = MM < 10 ? ('0' + MM) : MM
  let d = date.getDate()
  d = d < 10 ? ('0' + d) : d
  let h = date.getHours()
  h = h < 10 ? ('0' + h) : h
  let m = date.getMinutes()
  m = m < 10 ? ('0' + m) : m
  let s = date.getSeconds()
  s = s < 10 ? ('0' + s) : s
  return y + '-' + MM + '-' + d
}
/*
* 格式化日期，因为组件会1213，格式化成01:21:13
* value: 组件的值
* rangeTimeData: 所使用的时间区间
* */
export function getDateInfoTime(value, rangeTimeData) {
  const hours = rangeTimeData[0][value[0]]
  const minute = rangeTimeData[1][value[1]]
  const second = rangeTimeData[2][value[2]]
  const time = hours + ':' + minute + ':' + second
  return time
}
/*
* 创建时间选择区间
*
* */
export function setRangeTimeData() {
  const rangeTimeData = []
  const hours = Array.from(new Array(24).keys(), val => {
    return val < 10 ? '0' + val : val + ''
  })
  const minute = Array.from(new Array(60).keys(), val => {
    return val < 10 ? '0' + val : val + ''
  })
  rangeTimeData.push(hours)
  rangeTimeData.push(minute)
  rangeTimeData.push(minute)
  return rangeTimeData
}
// 格式化接口返回的日期
export function getDateInfo(value) {
  if (!value) {
    return ''
  }
  const date = new Date(value.replace(/-/g, '/'))
  const y = date.getFullYear()
  let MM = date.getMonth() + 1
  MM = MM < 10 ? ('0' + MM) : MM
  let d = date.getDate()
  d = d < 10 ? ('0' + d) : d
  let h = date.getHours()
  h = h < 10 ? ('0' + h) : h
  let m = date.getMinutes()
  m = m < 10 ? ('0' + m) : m
  let s = date.getSeconds()
  s = s < 10 ? ('0' + s) : s
  return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
}
